package com.hyr.springcloud.multi.service;

import com.hyr.springcloud.multi.dao.UserInfoRepository;
import com.hyr.springcloud.multi.domain.Order;
import com.hyr.springcloud.multi.domain.UserInfo;
import org.hibernate.validator.constraints.EAN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserService {
    @Autowired
    private JdbcTemplate orderJdbcTemplate;

    @Autowired

    private UserInfoRepository userInfoRepository;

    @Transactional
    public void createOrder(Order order){
        String update = "INSERT INTO order_info(price,content)VALUE(?,?);";
        orderJdbcTemplate.update(update,order.getPrice(),order.getContent());
        if (order.getContent().contains("error1")){
            throw  new RuntimeException("创建订单发生错误");
        }
        String updateuser = "update userinfo set balance=balance-? where id=?; ";
        UserInfo userInfo = userInfoRepository.findUserInfoById(1);
        userInfo.setBalance(userInfo.getBalance().subtract(order.getPrice()));
        userInfoRepository.save(userInfo);
        if (order.getContent().contains("error2")){
            throw  new RuntimeException("扣款发生错误");
        }

    }

    public Map<String,Object> userInfo(int userid){
        Map<String,Object> resutl = new HashMap<>();
        String query = "select * from order_info";
        String userquery = "select * from `userinfo` where id=?";
        SqlRowSet rowSet = orderJdbcTemplate.queryForRowSet(query);
        List<Order> orderList = new ArrayList<>();
        while (rowSet.next()){
            Order order = new Order();
            order.setContent(rowSet.getString("content"));
            order.setId(rowSet.getInt("id"));
            order.setPrice(rowSet.getBigDecimal("price"));
            orderList.add(order);
        }
        UserInfo userInfo = userInfoRepository.findUserInfoById(userid);
        resutl.put("user",userInfo);
        resutl.put("orderlist",orderList);
        return resutl;
    }
}
